const models = require('../models')
const sequelize = require("../models/index.js").sequelize

const {genPassword, getToken} = require('../utils/cryp')
const {ErrorModel} = require("../utils/resModel");
const login = async (ctx,body) => {
    const {username, password} = body
    console.log('====')
    try {
        const rows = await models.users.findOne({where: {username: username}});
        console.log('111')
        let newPassword = genPassword(password, rows['salt']);
        console.log('222',rows)
        console.log(newPassword , rows['password'])
        if (newPassword === rows['password']) {
            return rows;
        }else {
            return false
        }
    } catch (err) {
        ctx.body = new ErrorModel('登录失败')
    }
}
const generateRandomString = (length) => {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        result += characters[randomIndex];
    }
    return result;
}
const register = async (ctx,body) => {
    const {username, password} = body
    let userData = await models.users.findOne({where: {username: username}})
    if (userData && userData.dataValues) {
        ctx.body = new ErrorModel('用户名已存在')
        return false
    }else {
        const salt = generateRandomString(10);
        let newPassword = genPassword(password, salt)
        let data = {username: username, password: newPassword, salt: salt}
        const rows = await models.users.create(data); // 创建用户并保存到数据库
        return rows
    }
}


module.exports = {
    login,
    register
}
